/**
 * @Description: 请求封装
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 24/01/25 PM2:07
 */

import { onBeforeUnmount } from 'vue'
import { isFunction } from 'sf-utils2'
import { toSkipLoading } from '@/api/helper'
import { isObject } from 'lodash-es'

type TOption = {
  noLoading?: boolean
  requestKey?: string // 请求的自定义key 键名
}

type P = Promise<any> & { cancel?: () => void; TOption?: boolean }

const useReq = function <T extends P>(request: T, lock: Record<string, any>, option?: TOption): T {
  if (!isObject(lock)) throw new Error('lock参数必须是对象')

  const curRequestKey = option?.requestKey ?? '__requestPromise'

  /**
   * 取消
   */
  function cancel() {
    if (isFunction(request?.cancel)) request.cancel()
  }

  const noLoading = option?.noLoading ?? false

  if (isFunction(lock[curRequestKey]?.cancel)) lock[curRequestKey].cancel()

  request = toSkipLoading(request, noLoading) as T

  lock[curRequestKey] = request

  onBeforeUnmount(() => {
    cancel()
  })

  return request
}

useReq.ERR_CANCELED = 'ERR_CANCELED'

export { useReq }
